<script setup>
import MwTable from "./component/MwTableDriver";
import SearchTable from "./component/SearchDriver.vue";
import MwDialog from "@/components/Dialog";
import { ElMessage, ElMessageBox } from 'element-plus';

import { CirclePlus, VideoPlay } from '@element-plus/icons-vue';
import { ref, reactive, getCurrentInstance, onMounted, watch } from "vue";
import moment from "moment";

const instance = getCurrentInstance();
const _this = instance.appContext.config.globalProperties; //vue3获取当前this

// 生命周期
onMounted(() => {
  getTableData();
  getSelect();
});

let getTableData = () => {
  // 查询司机
  let paramsDriver = {
    ...pagination,
    ...searchForm
  };
  tablLoading.value = true;
  instance.proxy.$http.get('overview.getDriverList',{ params: paramsDriver }).then(res=>{
    let {content, totalElements} = res.data;
    tableData.value = content;
    pagination.total = totalElements;
    tablLoading.value = false;
  }).catch(err => tablLoading.value = false)
};

let getSelect = () => {
  instance.proxy.$http.get('archiveData.dictDetail', {params: {name: 'driver_education'}}).then(res=>{
    selectEducation.value = res.data;
  });
  instance.proxy.$http.get('archiveData.dictDetail', {params: {name: 'driver_health'}}).then(res=>{
    selectHealth.value = res.data;
  });
  instance.proxy.$http.get('archiveData.dictDetail', {params: {name: 'driver_gender'}}).then(res=>{
    selectGender.value = res.data;
  });
  instance.proxy.$http.get('archiveData.getAmbulanceSelect').then(res=>{
    selectVehicle.value = res.data.map(i => {
      i['label'] = i.selectName;
      i['value'] = i.id;
      return i;
    });
  });
};
// 下拉数据
const selectVehicle = ref([]);   // 救护车
const selectEducation = ref([]);   // Education
const selectHealth = ref([]);   // Health
const selectGender = ref([]);   // Gender


// 弹框数据
let dialogShow = ref(false);
let dialogTitle = ref(' Driver');
let dialogState = ref('Add'); //  Add Edit Detail 三种状态 根据状态来判断提交方法
let dialogRef = ref(null);
let dialogFrom = reactive({});
let dialogRules = reactive({
  drivernumber: [
    { required: true, message: 'Please input Camera ID', trigger: 'blur' },
    { pattern: /^[^\s]+(\s+[^\s]+)*$/, message: 'String cannot contain spaces', trigger: 'blur' }, 
  ],
  name: [
    { required: true, message: 'Please input Model', trigger: 'blur' },
    { pattern: /^[^\s]+(\s+[^\s]+)*$/, message: 'String cannot contain spaces', trigger: 'blur' }, 
  ]
});
let dialogSubmit = async () => {
  let formEl = dialogRef.value;
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      let url = dialogState.value == 'Add' ? 'archiveData.insertDriver' : 'archiveData.updateDriver';
      if (dialogState.value == 'Add') {
        instance.proxy.$http.post(url, dialogFrom).then(res=>{
          if (res.success) {
            onSearch();
            dialogClose();
          };
        });
      }else{
        instance.proxy.$http.put(url, dialogFrom).then(res=>{
          if (res.success) {
            onSearch();
            dialogClose();
          };
        });
      };
    } else {
      console.err('error submit!', fields);
    };
  });
};

let dialogClose = () => {
  dialogShow.value = false;
  dialogRef.value.resetFields();
  for(let item in dialogFrom){
    if(dialogFrom[item] instanceof Array){
      dialogFrom[item] = [];
    }else{
      dialogFrom[item] = '';
    };
  };
};

function openDialog(state) {
  dialogState.value = state;
  dialogShow.value = true;
  for(let item in dialogFrom){
    delete dialogFrom[item];
  };
};

// 表格数据
const tableData = ref([]);
const tablLoading = ref(false);
const pagination = reactive({
  page: 1,
  size: 10,
  total: 100
});
const searchForm = reactive({});
function onSearch(){
  getTableData();
};
function paginationChange(pagination){
  onSearch();
};

function onEdit(row){
  openDialog('Edit');
  for(let i in row) {
    if (i == 'licenseexpeirate') {
      dialogFrom['licenseexpeirate'] = row[i] ? moment(row[i]).format('YYYY-MM-DD') : '';
    }else{
      dialogFrom[i] = row[i];
    };
  };
};

function onDelete(row){
  ElMessageBox.confirm(
    'Delete Driver ？',
    'Delete',
    {
      confirmButtonText: 'Confirm',
      cancelButtonText: 'Cancel'
    }
  )
    .then(() => {
      instance.proxy.$http.delete('archiveData.deleteDriver', {data: {id: row.id + ''}}).then(res=>{
        onSearch();
        ElMessage({
          type: 'success',
          message: 'Delete Driver successfully',
        });
      });
    })
    .catch(() => {});
}

</script>
<template>
  <div class="table_index">
    <SearchTable 
      :searchForm="searchForm" 
      :selectGender="selectGender" 
      :selectVehicle="selectVehicle"
      @onSearch="onSearch"
      @addPeople="openDialog('Add')" />
    <div class="table_content">
      <mw-table
        v-loading="tablLoading"
        :data="tableData"
        :pagination="pagination"
        @paginationChange="paginationChange"
        @operate1="onEdit"
        @operate2="onDelete"
      ></mw-table>
    </div>
  </div>

  
  <mw-dialog
    :show="dialogShow"
    :title="dialogState + dialogTitle"
    width="920px"
    @submit="dialogSubmit"
    @close="dialogClose"
  >
    <el-form ref="dialogRef" class="dialog_form" :inline="true" :model="dialogFrom" label-width="170px" :rules="dialogRules">
      <el-form-item label="Number"  prop="drivernumber">
        <el-input v-model="dialogFrom.drivernumber" class="value_input" placeholder="Enter" clearable />
      </el-form-item>
      <el-form-item label="Name" prop="name">
        <el-input v-model="dialogFrom.name" class="value_input" placeholder="Enter" clearable />
      </el-form-item>
      <el-form-item label="Gender">
        <el-select
          class="value_input" 
          v-model="dialogFrom.sex"
          placeholder="Please select"
          filterable
          clearable
        >
          <el-option v-for="item in selectGender" :key="item.id" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="Age">
        <el-input type="number" v-model="dialogFrom.age" class="value_input" placeholder="Enter" clearable />
      </el-form-item>
      <el-form-item label="Education">
        <el-select
          class="value_input"
          v-model="dialogFrom.education"
          placeholder="Please select"
          filterable
          clearable
        >
          <el-option v-for="item in selectEducation" :key="item.id" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="Driving Experience">
        <el-input v-model="dialogFrom.experience" type="number" class="value_input" placeholder="Enter" clearable />
      </el-form-item>
      <el-form-item label="License Expiration Time">
        <el-date-picker
          style="--el-date-editor-width: 190px"
          v-model="dialogFrom.licenseexpeirate"
          value-format="YYYY-MM-DD"
          type="date"
          clearable
        />
      </el-form-item>
      <el-form-item label="Health">
        <el-select
          class="value_input"
          v-model="dialogFrom.health"
          placeholder="Please select"
          filterable
          clearable
        >
          <el-option v-for="item in selectHealth" :key="item.id" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="Using Vehicles">
        <el-select
          class="value_input"
          v-model="dialogFrom.ambulanceId"
          placeholder="Please select"
          filterable
          clearable
        >
          <el-option v-for="item in selectVehicle" :key="item.id" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
    </el-form>
  </mw-dialog>
</template>